import Tween = egret.Tween;

/**
 * Create by richliu1023
 * @date 16/5/19
 * @email richliu1023@gmail.com
 * @github https://github.com/RichLiu1023
 * @description a simple explanation
 */
class BaseDisplayApp extends eui.Component {
	protected static maskList:BaseDisplayApp[] = [];
	protected static _maskBg:egret.Shape;
	protected _parentSP:egret.DisplayObjectContainer = UIController.uiLayer;
	protected isShowMask:boolean = false;
	protected isClickMaskClose:boolean = true;
	protected maskAlpha:number = 0.75;
	private _appInfo:rm.AppInfo;

	public constructor() {
		super();
	}

	public get appInfo():rm.AppInfo {
		return this._appInfo;
	}

	public set appInfo( value:rm.AppInfo ) {
		this._appInfo = value;
	}

	public show( $parentContainer:egret.DisplayObjectContainer = null ):void {
		this._parentSP = $parentContainer || this._parentSP;
		this._parentSP || (this._parentSP = UIController.uiLayer);
		this.parent || this._parentSP.addChild( this );
		this.updateMaskBg();
	}

	public hide():void {
		this.removeMask();
		this.parent && this.parent.removeChild( this );
	}

	public onHide():void {
		Tween.removeTweens( this );
		rm.AppManager.hideApp( this._appInfo.appName );
	}

	private updateMaskBg():void {
		if ( this.isShowMask ) {
			BaseDisplayApp.maskList.push( this );
			if ( !BaseDisplayApp._maskBg ) {
				BaseDisplayApp._maskBg = new egret.Shape();
				BaseDisplayApp._maskBg.touchEnabled = true;
				BaseDisplayApp._maskBg.graphics.clear();
				BaseDisplayApp._maskBg.graphics.beginFill( 0x000000, 1 );
				BaseDisplayApp._maskBg.graphics.drawRect( 0, 0, GameConfig.STAGE_W, GameConfig.STAGE_H );
				BaseDisplayApp._maskBg.graphics.endFill();
			}
			BaseDisplayApp._maskBg.alpha = this.maskAlpha;
			BaseDisplayApp._maskBg.addEventListener( egret.TouchEvent.TOUCH_TAP, this.onClickMask, this );
			BaseDisplayApp._maskBg.parent || UIController.topLayer.addChildAt( BaseDisplayApp._maskBg, 0 );
		}
		else {
			this.removeMask();
		}
	}

	private removeMask():void {
		let idx = BaseDisplayApp.maskList.indexOf( this );
		( ~idx ) && BaseDisplayApp.maskList.splice( idx, 1 );
		BaseDisplayApp._maskBg && BaseDisplayApp._maskBg.removeEventListener( egret.TouchEvent.TOUCH_TAP,
																			  this.onClickMask,
																			  this );
		if ( BaseDisplayApp.maskList.length == 0 ) {
			BaseDisplayApp._maskBg && BaseDisplayApp._maskBg.parent && BaseDisplayApp._maskBg.parent.removeChild(
				BaseDisplayApp._maskBg );
		}
	}

	public closeAllPanelNoOwn():void {
		if ( this.appInfo.isSpecialInCloseAll ) {
			rm.AppManager.closeAllApp();
		}
		else {
			this.appInfo.isSpecialInCloseAll = true;
			rm.AppManager.closeAllApp();
			this.appInfo.isSpecialInCloseAll = false;
		}
	}

	private onClickMask():void {
		this.isClickMaskClose && this.onHide();
	}
}